<script setup>
import { SERVE_URL, imgSERVEURL, global } from '@utils/config';
import { ref, toRaw, nextTick, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import QrcodeVue from 'qrcode.vue';
import Type from '@components/search/type';
import Search from '@components/search/index';
import PageWrapper from '@components/PageWrapper.vue';
import { common, service } from '@utils';
import { Plus, Edit, Share, View, Delete, TurnOff, Open } from '@element-plus/icons-vue';
import { usePremission, useRole } from '@hooks';
import EditCom from './Edit';
import Detail from './Detail';
import homeActive from "../../services/homeActive";
// import noGoods from './noGoods';

const premission = usePremission({
  add: 'goods:addGoods', //新增
  view: 'goods:detailGoods', //详情
  share: 'bfqz:goods:share',
  del: 'goods:deleteGoods', //删除
  edit: 'goods:editGoods', //修改
  downShelves: 'goods:audit:downShelves', //   下架
  putShelves: 'goods:audit:putShelves', //    上架
  submitReviewApplication: 'goods:audit:submitReviewApplication', // 提交审核申请
  refusePutShelves: 'goods:audit:refusePutShelves', //拒绝上架
});

let searchs = reactive([
  {
    type: Type.INPUT,
    key: 'goodsId',
    width: 5,
    placeholder: '商品id',
    likes: true,
  },
  {
    type: Type.SELECT,
    key: 'companyCode',
    width: 5,
    placeholder: '商户名称',
    valueKey: 'companyCode',
  },
  {
    type: Type.SELECT,
    key: 'status',
    width: 4,
    valueKey: 'value',
    data: [],
    placeholder: '上架状态',
  },
  {
    type: Type.INPUT,
    key: 'name',
    width: 5,
    placeholder: '商品名称',
    likes: true,
  },
  {
    width: 4,
    type: Type.SEARCH_BUTTON,
  },
]);

if (premission.submitReviewApplication) {
  searchs.splice(1, 1);
}

const pageRef = ref();
const tableRef = ref();
const editRef = ref();
const detailRef = ref();
const noGoodsRef = ref();
const expressMethods = ref([]);
const newOrOld = ref([]);
const categorys = ref();
const codeList = ref()

let queryForm = {};
const onSearch = param => {
  queryForm = param;
  pageRef.value.refresh();
};

const getData = async ({ pageNum, pageSize }, cb) => {
  const list = await service.channelConfigApi.queryChannelNameByLoginUser({})
  if (list) {
    codeList.value = list.data;
  }
  const res = await service.bfqz.goodss(pageNum, pageSize, queryForm);
  res.success && cb(res);
  setTimeout(() => {
    tableRef.value.scrollTo(0, 0);
  }, 0);
};

const getGoodsQRCode = async (id) => {
  const res = await service.homeActive.getGoodsQRCode({goodsId: id});
  return res;
};

const getDictionary = async () => {
  const res = await service.auth.sysdirectListbyCode({ code: 'auditState,fastMail,newOrOld' });
  if (res) {
    res.forEach(item => {
      switch (item.typeCode) {
        case 'fastMail':
          expressMethods.value.push(item);
          break;
        case 'newOrOld':
          newOrOld.value.push(item);
          break;
        case 'auditState':
          if (!premission.submitReviewApplication) {
            searchs[2].data.push(item);
          } else {
            searchs[1].data.push(item);
          }
          break;
        case 'yesNo':
          // res[i].list.forEach((item) => {
          item.value === 'true' && (item.value = true);
          item.value === 'false' && (item.value = false);
          // })
          searchs[3].data = item;
          break;
        default:
          break;
      }
    });
    // for (let i = 0; i < res.length; i++) {
    //     if (res[i].typeCode === 'fastMail') {

    //     } else if (res[i].typeCode === '') {

    //     } else if (res[i].typeCode === 'auditState') {

    //     } else if (res[i].typeCode === 'yesNo') {
    //         res[i].list.forEach((item) => {
    //             item.val === 'true' && (item.val = true)
    //             item.val === 'false' && (item.val = false)
    //         })
    //         searchs[3].data = res[i].list
    //     }
    // }
  }
  if (!premission.submitReviewApplication) {
    const company = await service.auth.companyAll();
    searchs[1].data = company;
    searchs[1].data2 = company;
  } else {
    const company = await service.auth.companyAll();
    searchs[1].data2 = company;
  }
};

const getCategorys = async () => {
  const res = await service.bfqz.categoryCascader();
  categorys.value = res;
};

const showDetail = row => {
  // if (row.protect == undefined) {
  editRef.value.open(toRaw(row), true, '详情');
  // } else {
  //     detailRef.value.open(toRaw(row))
  // }
};

const changeState = async (row, auditState) => {
  const res = await service.bfqz.goodsEdit({ id: row.id, auditState });
  if (res.resultCode == 8200) {
    pageRef.value.refresh(true);
    ElMessage.success('修改成功');
  }
};

const setSubmitState = async row => {
  const res = await service.bfqz.goodsSubmit({ goodsId: row.goodsId });
  if (res.resultCode == 8200) {
    pageRef.value.refresh(true);
    ElMessage.success('提交成功');
  } else {
    ElMessage.error('提交失败');
  }
};

const upRow = async row => {
  const res = await service.bfqz.putShelves({ goodsId: row.goodsId });
  if (res.resultCode == 8200) {
    ElMessage.success('上架成功');
    pageRef.value.refresh(true);
  } else {
    ElMessage.error('上架失败');
  }
  // ElMessageBox.confirm('是否同意此商品上架', '提示', {
  //     type: 'warning'
  // }).then(async () => {
  // })
};
// auditState 0:待审核 1:上架 2:下架 3:拒绝上架审核 downShelves
const downRow = async row => {
  if (dialogVisible.type == 3) {
    const res = await service.bfqz.refusePutShelves({
      goodsId: dialogVisible.id,
      // auditState: dialogVisible.type,
      content: dialogVisible.content,
    });
    if (res.resultCode == 8200) {
      ElMessage.success('拒绝成功');
    } else {
      ElMessage.error('拒绝上架失败');
      return;
    }
  } else if (dialogVisible.type == 2) {
    const res = await service.bfqz.downShelves({
      goodsId: dialogVisible.id,
      // auditState: dialogVisible.type,
      content: dialogVisible.content,
    });
    if (res.resultCode == 8200) {
      ElMessage.success('下架成功');
    } else {
      ElMessage.error('下架失败');
      return;
    }
  }
  pageRef.value.refresh(true);
  dialogVisible.dialogVisibleShow = false;
  dialogVisible.content = null;
};

const deleteRow = async row => {
  ElMessageBox.confirm('是否删除此商品', '提示', {
    type: 'warning',
  }).then(async () => {
    const res = await service.bfqz.goodsDelete(row.goodsId);
    if (res) {
      ElMessage.success('删除成功');
      pageRef.value.refresh(true);
    }
  });
};
getDictionary();
getCategorys();

const width = (function (premission) {
  let width = 24;
  premission.view && (width += 33);
  premission.share && (width += 33);
  premission.edit && (width += 33 * 2);
  premission.del && (width += 33);
  return Math.max(width, 72);
})(premission);

let dialogVisible = reactive({
  dialogVisibleShow: false,
  name: '',
  url: '',
  code: ''
});
const showQrCode = async (val, type) => {
  dialogVisible.dialogVisibleShow = true;
  dialogVisible.type = type;
  if (dialogVisible.type == 1) {
    dialogVisible.name = val.name || '未命名商品';
    const res = {'goodsId':val.goodsId}
    dialogVisible.url = `https://w.wthigh.com/pages/goods/detail/index?query=${JSON.stringify(res)}`;
  } else if (dialogVisible.type == 3) {
    dialogVisible.name = '拒绝上架商品';
    dialogVisible.id = val.goodsId;
  } else if (dialogVisible.type == 2) {
    dialogVisible.name = '下架商品';
    dialogVisible.id = val.goodsId;
  } else if (dialogVisible.type == 4) {
    dialogVisible.name = val.name || '未命名商品'
    dialogVisible.id = val.goodsId
  }
};

const changeCode = async (val, goodsId) => {
  dialogVisible.code = val || '';
  //const res = await getGoodsQRCode(goodsId);
  //res.data.channelCode = val || '';
  const res = {'goodsId':goodsId, 'channelCode': val || ''}
  dialogVisible.url = `https://w.wthigh.com/pages/goods/detail/index?query=${JSON.stringify(res)}`;
  //dialogVisible.url = `alipays://platformapi/startapp?appId=${global.appId}&page=pages/shopDetail/shopDetail?id%3D${dialogVisible.id}%26channelCode%3D${dialogVisible.code}`

}

const close = () => {
  dialogVisible.dialogVisibleShow = false
  dialogVisible.code = ''
  dialogVisible.url = ''
}

const download = () => {
  //获取canvas标签
  let canvas = document.getElementsByTagName('canvas');
  //创建a标签
  let a = document.createElement('a');
  //获取二维码的url并赋值为a.href
  a.href = canvas[0].toDataURL('img/png');
  //设置下载文件的名字
  a.download = dialogVisible.name;
  //点击事件，相当于下载
  a.click();
  //提示信息
  this.$message.warn('下载中，请稍后...');
};

const handleClose = () => {
  ElMessageBox.confirm('确定关闭弹窗嘛?')
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
</script>
<template>
  <section class="main-white">
    <search :items="searchs" @filter="onSearch" />
    <div class="margin-bottom10" v-if="premission.add">
      <el-button type="primary" :icon="Plus" @click="editRef.open(undefined, false, '新增')">添加</el-button>
    </div>
    <page-wrapper @get-data="getData" ref="pageRef">
      <template v-slot:default="props">
        <vxe-table class="mytable-scrollbar" ref="tableRef" :loading="props.loading" :data="props.tableData.records"
          :max-height="common.tableHeight(true, premission.add ? 2 : 1)" highlight-hover-row round stripe border>
          <vxe-column field="goodsId" title="商品ID" width="160" />
          <vxe-column field="name" title="商品名称" width="150" />
          <vxe-column title="商品图片" width="140">
            <template #default="{ row }">
              <div class="imgBox" style="height: 130px">
                <el-image style="width: 100px; height: 100px" :src="`${imgSERVEURL}${row.cover}`" fit="contain"
                  :preview-src-list="[`${imgSERVEURL}${row.cover}`]">
                  <template #error>
                    <div class="image-slot">
                      <el-image style="width: 100px; height: 100px"
                        :src="`https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png`"
                        fit="contain"></el-image>
                    </div>
                  </template>
                </el-image>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="商户名称" width="220" field="companyName" />
          <vxe-column title="上架状态" width="100">
            <template #default="{ row }">
              {{ common.getValueByKey('value', row.status, searchs[!premission.submitReviewApplication ? 2 : 1].data,
                'label') }}
            </template>
          </vxe-column>
          <vxe-column field="saleNum" title="销量" width="100" />
          <vxe-column title="备注" field="content" width="100" />
          <vxe-column field="updateTime" title="最新操作时间" width="180" />
          <vxe-column title="操作" min-width="230" fixed="right">
            <template #default="{ row }">
              <section class="flex-align flex-wrap">
                <el-tooltip v-if="!premission.share && row.status == 1" effect="dark" content="分享二维码" placement="top"
                  :enterable="false">
                  <el-button type="primary" plain :icon="Share" circle size="small"
                    @click="showQrCode(row, 1)"></el-button>
                </el-tooltip>
                <el-tooltip v-if="!premission.share && row.status == 1" effect="dark" content="渠道二维码" placement="top"
                  :enterable="false">
                  <el-button type="primary" plain :icon="Share" circle size="small"
                    @click="showQrCode(row, 4)"></el-button>
                </el-tooltip>
                <el-tooltip v-if="premission.view" effect="dark" content="详情" placement="top" :enterable="false">
                  <el-button type="primary" plain :icon="View" circle size="small" @click="showDetail(row)"></el-button>
                </el-tooltip>
                <el-tooltip v-if="premission.edit && (row.status == 2 || row.status == 3)" effect="dark" content="修改"
                  placement="top" :enterable="false">
                  <el-button type="primary" :icon="Edit" size="small" circle
                    @click="editRef.open(row, false, '修改')"></el-button>
                </el-tooltip>
                <el-tooltip v-if="premission.downShelves && row.status == 1" effect="dark" content="下架" placement="top"
                  :enterable="false">
                  <!-- <el-popconfirm
                                    v-if="premission.downShelves && row.status == 1"
                                    confirm-button-text="确认"
                                    cancel-button-text="取消"
                                    title="确认下架此商品吗?"
                                    width="200"
                                    @confirm="changeState(row, 3)"
                                >
                                    <template #reference> -->
                  <el-button type="danger" :icon="TurnOff" size="small" circle @click="showQrCode(row, 2)"></el-button>
                  <!-- </template>
                                </el-popconfirm> -->
                </el-tooltip>
                <!-- <el-tooltip
                                    v-if="premission.audit && row.status == 0"
                                    effect="dark"
                                    content="确认上架"
                                    placement="top"
                                    :enterable="false"
                                > -->
                <el-popconfirm v-if="premission.putShelves && row.status == 0" confirm-button-text="确认"
                  cancel-button-text="取消" title="确认上架此商品吗?" width="200" @confirm="upRow(row, true)">
                  <template #reference>
                    <el-button type="success" :icon="Open" size="small" circle></el-button>
                  </template>
                </el-popconfirm>
                <!-- </el-tooltip> -->

                <el-tooltip v-if="premission.refusePutShelves && row.status == 0" effect="dark" content="拒绝上架"
                  placement="top" :enterable="false">
                  <!-- <el-popconfirm
                                    v-if="premission.audit && row.status == 0"
                                    confirm-button-text="确认"
                                    cancel-button-text="取消"
                                    title="拒绝上架此商品吗?"
                                    width="200"
                                    @confirm="showQrCode(row, 2)"
                                > -->
                  <!-- <template #reference> -->
                  <el-button type="danger" :icon="Open" size="small" circle @click="showQrCode(row, 3)"></el-button>
                  <!-- </template> -->
                  <!-- </el-popconfirm> -->
                </el-tooltip>
                <el-popconfirm v-if="premission.submitReviewApplication && (row.status == 2 || row.status == 3)"
                  confirm-button-text="确认" cancel-button-text="取消" icon-color="#626AEF" title="确认提交此商品上架审核吗?"
                  @confirm="setSubmitState(row)">
                  <template #reference>
                    <el-button type="success" :icon="Open" size="small" circle></el-button>
                  </template>
                </el-popconfirm>
                <el-tooltip v-if="premission.del && (row.status == 2 || row.status == 3)" effect="dark" content="删除"
                  placement="top" :enterable="false">
                  <el-button type="danger" plain :icon="Delete" size="small" circle @click="deleteRow(row)"></el-button>
                </el-tooltip>
              </section>
            </template>
          </vxe-column>
        </vxe-table>
      </template>
    </page-wrapper>
    <el-dialog v-model="dialogVisible.dialogVisibleShow" width="360px">
      <template #header="{ titleId }">
        <div class="my-header">
          <h4 :id="titleId">{{ dialogVisible.name }}</h4>
        </div>
      </template>
      <div>
        <qrcode-vue v-if="dialogVisible.type == 1 || (dialogVisible.type == 4 && dialogVisible.code != '')"
          :value="dialogVisible.url" :size="260"></qrcode-vue>
        <div v-if="dialogVisible.type == 4" style="width:100%;margin-top:60px;">
          渠道编码：<el-select v-model="dialogVisible.code" @change="changeCode(dialogVisible.code, dialogVisible.id)" style="" placeholder="请选择渠道" clearable>
            <el-option v-for="(item, index) in codeList" :key="index" :label="item.channelName"
              :value="item.channelCode" />
          </el-select>
        </div>
        <div v-if="dialogVisible.type == 2 || dialogVisible.type == 3">
          <el-input type="textarea" style="width: 280px" rows="6" show-word-limit
            :placeholder="dialogVisible.name == '下架商品' ? '请备注下架原因' : '请备注拒绝原因'" v-model.trim="dialogVisible.content"
            clearable maxlength="100"></el-input>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button v-if="dialogVisible.type == 1 || (dialogVisible.type == 4 && dialogVisible.code != '')"
            type="primary" @click="download">下载</el-button>
          <el-button v-if="dialogVisible.type == 2 || dialogVisible.type == 3" type="danger" @click="downRow">
            {{ dialogVisible.name == '下架商品' ? '下架' : '拒绝' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    <detail ref="detailRef" :categorys="categorys" :expressMethods="expressMethods" :newOrOld="newOrOld" />
    <edit-com ref="editRef" :expressMethods="expressMethods" :newOrOld="newOrOld" :categorys="categorys"
      @refresh="flag => pageRef.refresh(flag)" />
    <!-- <noGoods ref="noGoodsRef" @refresh="flag => pageRef.refresh(flag)" /> -->
  </section>
</template>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  display: flex;
  justify-content: center;
}

/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

/*滚动条的轨道*/
.mytable-scrollbar ::-webkit-scrollbar-track {
  background-color: #ffffff;
}

/*滚动条里面的小方块，能向上向下移动*/
.mytable-scrollbar ::-webkit-scrollbar-thumb {
  background-color: #bfbfbf;
  border-radius: 5px;
  border: 1px solid #f1f1f1;
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

.mytable-scrollbar ::-webkit-scrollbar-thumb:hover {
  background-color: #a8a8a8;
}

.mytable-scrollbar ::-webkit-scrollbar-thumb:active {
  background-color: #787878;
}

/*边角，即两个滚动条的交汇处*/
.mytable-scrollbar ::-webkit-scrollbar-corner {
  background-color: #ffffff;
}

.imgBox {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
